/**
 * Android FriendFeed Client
 * Copyright (C) 2010 E & B Labs
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.eblabs.androidfriendfeedclient;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.eblabs.friendfeed.ApiException;
import net.eblabs.friendfeed.FriendFeedAPI;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author epplestun
 */
public class FriendfeedAddEntryActivity extends Activity {

    /**
     * Tokinizer especial para MultiAutocompleteTextView.
     */
    private static class SpaceTokenizer implements
            MultiAutoCompleteTextView.Tokenizer {
        @Override
        public int findTokenEnd(final CharSequence text, final int cursor) {
            int pos = text.toString().indexOf(' ', cursor);

            if (pos < 0) {
                return text.length() - 1;
            } else {
                return pos - 1;
            }
        }

        @Override
        public int findTokenStart(final CharSequence text, final int cursor) {
            int pos = text.toString().lastIndexOf(' ', cursor);

            if (pos < 0) {
                return 0;
            } else {
                return pos + 1;
            }
        }

        @Override
        public CharSequence terminateToken(final CharSequence text) {
            String textStr = text.toString();

            if (textStr.endsWith(" ")) {
                return textStr;
            } else {
                return textStr + " ";
            }
        }
    }

    /**
     * xx.
     */
    private TextView attachments;

    /**
     * xx.
     */
    private ArrayList<String> attachmentsList;

    @Override
    public final void onCreate(final Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.newentry);

        setTitle(R.string.add_entry_title);

        this.attachmentsList = new ArrayList<String>();

        final Preferences preferences = Preferences.getInstance(this);
        FriendFeedAPI api = FriendFeedAPI.getInstance(
                preferences.getUsername(), preferences.getRemoteKey());

        final MultiAutoCompleteTextView toTextView =
                (MultiAutoCompleteTextView) findViewById(
                R.id.autocomplete_friends);
        toTextView.setTokenizer(new SpaceTokenizer());

        final EditText entryEditText = (EditText) findViewById(R.id.entry_text);
        ImageButton sendButton =
                (ImageButton) findViewById(R.id.send_new_entry);
        ImageButton addFileButton = (ImageButton) findViewById(R.id.add_file);
        this.attachments = (TextView) findViewById(R.id.attachments);

        try {
            JSONObject friends = api.getFriends();

            ArrayList<String> friendsArray = new ArrayList<String>();
            for (int i = 0; i < friends.getJSONArray("feeds").length(); i++) {
                String id = friends.getJSONArray("feeds").getJSONObject(i).
                        getString("id");
                friendsArray.add(id);
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    R.layout.autocompleteitem, friendsArray);
            toTextView.setAdapter(adapter);

            final Activity activity = this;

            addFileButton.setOnClickListener(new ImageButton.OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                    startActivityForResult(intent, 1);
                }
            });

            sendButton.setOnClickListener(new ImageButton.OnClickListener() {
                public void onClick(View v) {
                    FriendFeedAPI api = FriendFeedAPI.getInstance(
                            preferences.getUsername(),
                            preferences.getRemoteKey());

                    try {
                        String to = toTextView.getText().toString()
                                .replace(" ", ",");
                        String body = entryEditText.getText().toString();

                        if (attachmentsList.size() > 0) {
                            ArrayList<File> fileList = new ArrayList<File>();
                            for (int i = 0; i < attachmentsList.size(); i++) {
                                File f = new File(attachmentsList.get(i));
                                fileList.add(f);
                            }

                            api.addNewEntry(body, to, fileList);
                        } else {
                            api.addNewEntry(body, to, null);
                        }

                        Toast.makeText(activity, R.string.send_comment_ok,
                                Toast.LENGTH_LONG).show();
                    } catch (ApiException ex) {
                        Log.d(FriendfeedAddEntryActivity.class.getName(),
                                ex.getMessage());
                    } catch (IOException ex) {
                        Log.d(FriendfeedAddEntryActivity.class.getName(),
                                ex.getMessage());
                    } catch (JSONException ex) {
                        Log.d(FriendfeedAddEntryActivity.class.getName(),
                                ex.getMessage());
                    } catch (URISyntaxException ex) {
                        Log.d(FriendfeedAddEntryActivity.class.getName(),
                                ex.getMessage());
                    }
                }
            });
        } catch (ApiException ex) {
            Logger.getLogger(FriendfeedAddEntryActivity.class.getName()).
                    log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FriendfeedAddEntryActivity.class.getName()).
                    log(Level.SEVERE, null, ex);
        } catch (JSONException ex) {
            Logger.getLogger(FriendfeedAddEntryActivity.class.getName()).
                    log(Level.SEVERE, null, ex);
        }

    }

    /* {@inheritDoc}. */
    @Override
    protected final void onStop() {
        super.onStop();
    }

    @Override
    protected final void onActivityResult(final int requestCode, final int
                     resultCode, final Intent i) {
        super.onActivityResult(requestCode, resultCode, i);

        final Activity activity = this;

        if (requestCode == 1) {
            Uri uri = i.getData();

            if (uri != null) {
                Cursor cursor = getContentResolver().query(uri, null, null,
                        null, null);
                cursor.moveToFirst();
                String imageFilePath = cursor.getString(1);
                cursor.close();

                // Guardamos el fichero
                this.attachmentsList.add(imageFilePath);

                String fileList = new String();
                for (int k = 0; k < this.attachmentsList.size(); k++) {
                    fileList += this.attachmentsList.get(k) + "\n";
                }

                this.attachments.setText(fileList);

                Toast.makeText(activity, R.string.file_attached_message,
                        Toast.LENGTH_LONG).show();
            }
        }
    }
}